#include <QDebug>
#include <QApplication>
#include "qsystemhotkey.h"

QSystemHotkey::QSystemHotkey(){
    running = false;
}

void QSystemHotkey::addKey(int keyID, UINT holdKey, char charKey){
    hotkeys.push_back(keyID);
    RegisterHotKey(NULL,keyID,holdKey | MOD_NOREPEAT,charKey);
}

void QSystemHotkey::removeKey(int keyID){
    for (int i = 0; i < (int)hotkeys.size(); ++i) {
        if(hotkeys.at(i) == keyID){
            UnregisterHotKey(NULL,hotkeys.at(i));
            hotkeys.erase(hotkeys.begin() + i);
        }
    }
}

int QSystemHotkey::getHotkey(int position){
    return hotkeys.at(position);
}

void QSystemHotkey::beginHotkeys(){
    running = true;
    listen();
}

void QSystemHotkey::haltHotkeys(){
    running = false;
}

void QSystemHotkey::listen(){
    while(running){
        GetMessage(&msg,NULL,0,0);
        TranslateMessage(&msg);
        DispatchMessage(&msg);
        if (msg.message == WM_HOTKEY){
            for (int i = 0; i < (int)hotkeys.size(); ++i) {
                if (msg.wParam == (unsigned int)hotkeys.at(i)) {emit_signal(i); qDebug()<< "Signal emited";}
            }
        }
    }
}

void QSystemHotkey::emit_signal(int position){
    emit runHotkey(getHotkey(position));
}

// hellothread/hellothread.cpp
void QSystemHotkey::run()
{
     qDebug() << "hello from worker thread " << thread()->currentThreadId();

        addKey(200,MOD_ALT,' ');
//        hotkeys->addKey(300,MOD_CONTROL,'X');
       // addKey(400,MOD_CONTROL,'Q');
     //   QApplication::processEvents();

        while(1)
        {
            listen();
        }


//     while(1)
//     {
//         qDebug()<< "runing";
//         msleep(500);
//     }



//     //--- hot key ----
//        hotkeys = new QSystemHotkey;
//        connect(hotkeys, SIGNAL(runHotkey(int)),this,SLOT(hotkeyPressed(int)));

//        hotkeys->addKey(200,MOD_ALT,' ');
//        hotkeys->addKey(300,MOD_CONTROL,'X');
//        hotkeys->addKey(400,MOD_CONTROL,'Q');
//        QApplication::processEvents();
//        beginHotkeys();
//        // does not return!!!!!

}
